package com.tdam2011.grupo02.ui;

import java.util.Calendar;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.compatibility.ActionBarActivity;
import com.tdam2011.grupo02.connectivity.ConnectivityInformationSingleton;
import com.tdam2011.grupo02.domain.DialogInfo;
import com.tdam2011.grupo02.domain.Usuario;
import com.tdam2011.grupo02.data.OnSendingInterface;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class RegistrarUsuarioActivity extends ActionBarActivity implements OnSendingInterface{

	private EditText txtUsuario;
	private EditText txtPassword;
	private EditText txtPasswordRepeat;
	private EditText txtNombre;
	private EditText txtMail;
	private EditText txtFechaNacimiento;
	private ImageButton btnFechaNacimiento;
	private Button btnRegistrar;
	private int mDay;
	private int mMonth;
	private int mYear;
	private OnDateSetListener datePickerListener;
	private String errorMessage;
	private NotificationManager notificationManager;
	private Notification notification;

	private static final String TAG = "Register";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registrar_usuario);

		setTitle(R.string.txtvRegistrarUsuario);

		txtUsuario = (EditText) findViewById(R.id.txt_registrar_usuario);
		txtPassword = (EditText) findViewById(R.id.txt_registrar_password);
		txtPasswordRepeat = (EditText) findViewById(R.id.txt_registrar_password_repetir);
		txtNombre = (EditText) findViewById(R.id.txt_registrar_nombre);
		txtMail = (EditText) findViewById(R.id.txt_registrar_mail);
		txtFechaNacimiento = (EditText) findViewById(R.id.txt_registrar_fecha_nacimiento);
		btnFechaNacimiento = (ImageButton) findViewById(R.id.imgbtn_registrar_fecha_nacimiento);
		btnRegistrar = (Button) findViewById(R.id.btn_registar);

		btnFechaNacimiento.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(DialogInfo.TYPE_DATE_PICKER);
			}
		});

		btnRegistrar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (ConnectivityInformationSingleton
						.getInstance(RegistrarUsuarioActivity.this)
						.getConnectivityInformation()
						.isInternetConnectionAvailable()) {

					if (validarDatosIngresados()) {
						Usuario user = new Usuario();

						user.set_id(txtUsuario.getText().toString());
						user.setPassword(txtPassword.getText().toString());
						user.setNombreCompleto(txtNombre.getText().toString());
						user.setMail(txtMail.getText().toString());
						user.setFechaNacimiento(txtFechaNacimiento.getText()
								.toString());

						if (user.get_id().length() > 4) {
							if (user.getPassword().length() > 5) {
								
								ContactActionControllerSingleton
								.getInstance(RegistrarUsuarioActivity.this)
								.getContactActionController()
								.registerUser(RegistrarUsuarioActivity.this, user);

							} else
								Toast.makeText(
										RegistrarUsuarioActivity.this,
										getString(R.string.condicionMinimaContraseniaPerfil),
										Toast.LENGTH_LONG).show();
						} else {
							Toast.makeText(
									RegistrarUsuarioActivity.this,
									getString(R.string.perfilCondicionNombreUsuario),
									Toast.LENGTH_LONG).show();
						}

					} else
						showDialog(DialogInfo.TYPE_ALERT_WRONG_USER_PASSWORD);
				} else
					mensajeConexionInternet();
			}

		});

		datePickerListener = new DatePickerDialog.OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				setDate();
				mYear = year;
				mMonth = monthOfYear + 1;
				mDay = dayOfMonth;
				setFechaNacimiento(mDay, mMonth, mYear);
			}
		};

		setDate();
		
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	}

	private boolean validarDatosIngresados() {
		if (this.txtUsuario.getText().toString().trim().length() == 0
				|| this.txtPassword.getText().toString().trim().length() == 0
				|| this.txtPasswordRepeat.getText().toString().trim().length() == 0
				|| this.txtNombre.getText().toString().trim().length() == 0
				|| this.txtFechaNacimiento.getText().toString().trim().length() == 0) {
			errorMessage = getString(R.string.msgDataRequiredError);
			return false;
		}
		if (!txtPassword.getText().toString()
				.equals(txtPasswordRepeat.getText().toString())) {
			errorMessage = getString(R.string.msgPasswordsError);
			return false;
		}
		return true;
	}

	private void setDate() {
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
	}

	private void setFechaNacimiento(int day, int month, int year) {
		this.txtFechaNacimiento.setText(day + "/" + month + "/" + year);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case DialogInfo.TYPE_DATE_PICKER:
			dialog = new DatePickerDialog(this, datePickerListener, mYear,
					mMonth, mDay);
			break;
		case DialogInfo.TYPE_ALERT_WRONG_USER_PASSWORD:
			dialog = ErrorDialog();
			break;
		}
		return dialog;
	}

	private Dialog ErrorDialog() {
		DialogInfo aux = new DialogInfo();
		aux.setTitle(getString(R.string.errorDialogTitle));
		aux.setBtLabelOk(getString(R.string.alertBtnOk));
		aux.setMessage(errorMessage);
		aux.setType(DialogInfo.TYPE_ALERT_WRONG_USER_PASSWORD);

		Dialog dialog = new AlertDialog.Builder(this)
				.setIcon(R.drawable.icon_alert).setTitle(aux.getTitle())
				.setPositiveButton(aux.getBtLabelOk(), null)
				.setMessage(aux.getMessage()).create();

		return dialog;
	}

	private void mensajeConexionInternet() {
		int icon = R.drawable.quick_action_msgweb;
		CharSequence tickerText = getString(R.string.notificationTickerText);
		long when = System.currentTimeMillis();
		String title = getString(R.string.registroDeUsuario);
		String text = getString(R.string.msgNoInternetConnection);

		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

		Intent notificationIntent = new Intent(RegistrarUsuarioActivity.this,
				MensajeWebNotificacionActivity.class);
		notificationIntent.putExtra("contacto", title);
		notificationIntent.putExtra("mensaje", text);
		PendingIntent contentIntent = PendingIntent.getActivity(
				RegistrarUsuarioActivity.this, 0, notificationIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		Notification notification = new Notification(icon, tickerText, when);
		notification.setLatestEventInfo(RegistrarUsuarioActivity.this, title,
				text, contentIntent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		mNotificationManager.notify(1, notification);
		Intent intent = new Intent(RegistrarUsuarioActivity.this,
				LoginFragmentActivity.class);
		startActivity(intent);
	}

	private void showNotificationRegistering() {
		notification = new Notification(R.drawable.user_registering,
				getString(R.string.userRegistrationNotificationTitle),
				System.currentTimeMillis());

		PendingIntent contentIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, new Intent(),
				PendingIntent.FLAG_UPDATE_CURRENT);

		notification.setLatestEventInfo(this,
				getString(R.string.userRegistrationNotificationTitle),
				getString(R.string.userRegisteringNotificationMessage),
				contentIntent);

		notification.flags = Notification.FLAG_ONGOING_EVENT;

		notificationManager.notify(R.string.userRegistrationNotificationTitle, notification);
	}

	private void updateNotificationRegistered() {

		PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
				new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);

		notification.flags = Notification.FLAG_AUTO_CANCEL;
		notification.defaults |= Notification.DEFAULT_SOUND;

		notification.icon = R.drawable.user_registered;
		notification.setLatestEventInfo(this,
				getString(R.string.userRegistrationNotificationTitle),
				getString(R.string.registeredUserNotificationMessage), contentIntent);

		notificationManager.notify(R.string.userRegistrationNotificationTitle, notification);
	}

	private void updateRegisterErrorNotification() {
		PendingIntent contentIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, new Intent(),
				PendingIntent.FLAG_UPDATE_CURRENT);

		notification.flags = Notification.FLAG_AUTO_CANCEL;
		notification.defaults |= Notification.DEFAULT_SOUND;

		notification.icon = R.drawable.user_register_error;
		notification.setLatestEventInfo(this,
				getString(R.string.userRegistrationNotificationTitle),
				getString(R.string.userExistsNotificationErrorMessage), contentIntent);

		notificationManager.notify(R.string.userRegistrationNotificationTitle, notification);
	}

	@Override
	public void onSending() {
		showNotificationRegistering();
	}

	@Override
	public void onSuccess() {
		updateNotificationRegistered();
		finish();
	}

	@Override
	public void onError() {
		updateRegisterErrorNotification();
	}
}
